package com.android.kmlmrg.services.rest.method;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import org.json.JSONObject;

import android.app.Application;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;

import com.android.kmlmrg.R;
import com.android.kmlmrg.event.RestUpdateUserPhotoEvent;
import com.android.kmlmrg.listener.custom.RestUpdateUserPhotoListener;
import com.android.kmlmrg.model.ApiSession;
import com.android.kmlmrg.model.User;
import com.android.kmlmrg.services.ServiceController;

public class UpdateUserPhoto extends AsyncTask<Void, Integer, Bitmap> {
	/**LOG**/
	private static final  String LOG_TAG = UpdateUserPhoto.class.getName();

	private final static String METHODE_NAME = "/updateUserPhoto";

	private static String PHOTO_STREAM_FIELD = "photoStream";

	private  User user;

	private String imageByteString;

	private static  ArrayList<RestUpdateUserPhotoListener> listeners = new ArrayList<RestUpdateUserPhotoListener>();

	private Application application;
	private int code;

	public UpdateUserPhoto(Application pApplication, User pUser , String pImageByteString) {
		application =pApplication;
		Log.i(LOG_TAG, "START - Construct UpdateUserPhoto");
		user = pUser;
		imageByteString = pImageByteString;

		Log.i(LOG_TAG, "IMAGE " + imageByteString );
		Log.i(LOG_TAG, "END - Construct UpdateUserPhoto");
	}


	protected Bitmap doInBackground(Void... sUrl) {
		try {
			Log.i(LOG_TAG, "START - doInBackground");
			String vUrl = this.application.getString(R.string.user_endpoint) + METHODE_NAME + "/" + user.getIdentifiant();

			ApiSession vApiSession =  ServiceController.getInstance().getApiSession() ;
			JSONObject vJsonObject = new JSONObject();				
			vJsonObject.put(ApiSession.WSCALLERID, vApiSession.getWsCallerId());
			vJsonObject.put(ApiSession.TIMESTAMP, vApiSession.getTimesTamp());
			vJsonObject.put(ApiSession.HASH, vApiSession.getHash());
			vJsonObject.put(PHOTO_STREAM_FIELD, imageByteString);
			String message = vJsonObject.toString();

			HttpURLConnection httpcon = (HttpURLConnection) ((new URL(vUrl).openConnection()));

			httpcon.setRequestProperty("Content-Type", "application/json");
			httpcon.setRequestProperty("Accept", "application/json");
			httpcon.setRequestMethod("POST");

			httpcon.setDoInput(true);
			httpcon.setDoOutput(true);
			httpcon.setFixedLengthStreamingMode(message.getBytes().length);
			httpcon.connect();


			OutputStream os = new BufferedOutputStream(httpcon.getOutputStream());
			os.write(message.getBytes());
			//clean up
			os.flush();


			// this will be useful so that you can show a typical 0-100% progress bar
			int fileLength = httpcon.getContentLength();

			code = httpcon.getResponseCode();

			// download the file

			InputStream input = httpcon.getInputStream();

			Bitmap bitmap = BitmapFactory.decodeStream(input);
			os.flush();
			os.close();
			input.close();	
			Log.i(LOG_TAG, "END - doInBackground");

			return bitmap;
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}





	@Override
	protected void onPostExecute(Bitmap result) {
		Log.i(LOG_TAG, "START - onPostExecute ");
		Log.i(LOG_TAG, "CODE :  " +  code );
		Log.i(LOG_TAG, "RESULT :  " +  result );

		RestUpdateUserPhotoEvent vEvent = new RestUpdateUserPhotoEvent(this, Integer.parseInt(user.getIdentifiant()), result);
		fireEvent(vEvent);

		Log.i(LOG_TAG, "END - onPostExecute ");

	}






	private void fireEvent( RestUpdateUserPhotoEvent pEvent ){	
		Log.i(LOG_TAG, "END - fireEvent(HttpResponse response) ");
		for(RestUpdateUserPhotoListener listener : listeners){
			listener.resultUpdateUserPhotoRequest( pEvent );
		}
		Log.i(LOG_TAG, "END - fireEvent(HttpResponse response) ");
	}

	public static void addListener ( RestUpdateUserPhotoListener pListener ){
		listeners.add(pListener);
	}

	public static void removeListener( RestUpdateUserPhotoListener pListener ){
		listeners.remove(pListener);
	}



}
